<template>
	<view>
		<uni-file-picker class="mb_30 mt_30" :value="filePathsList" :auto-upload="false" file-mediatype="image"
			mode="grid" file-extname="png,jpg,jpeg" :limit="limit||6" @select="select" @delete="handleDelete"
			@success="success" />
	</view>
</template>

<script>
	import {
		CONFIG
	} from '@/config/app'
	export default {
		model: {
			event: "inputFun",
		},
		props:["inputName",'limit'],
		name:"addImg",
		data() {
			return {
				filePathsList:[],
				Url: CONFIG.HTTP_REQUEST_URL + 'app-api/infra/file/upload',
			};
		},
		watch: {
			inputName(newVal) {
			  if (this.inputName) {
			    this.filePathsList = JSON.parse(this.inputName)
			  }
			},
		},
		
		methods:{
			handleDelete(err) { // 删除图片
				const num = this.filePathsList.findIndex(v => v.url === err.tempFilePath);
				this.filePathsList.splice(num, 1);
				this.$nextTick(() => {
					this.$emit('inputFun',  JSON.stringify(this.filePathsList))
				})
			},
			select(e) {
				let that = this
				uni.showLoading({
					title: "上传中"
				});
				const tempFilePaths = e.tempFilePaths;
				for (var i = 0; i < tempFilePaths.length; i++) {
					const tempFile = e.tempFiles[i];
					uni.uploadFile({
						url: this.Url,
						header: {
							'token': uni.getStorageSync('token'),
						},
						filePath: tempFilePaths[i],
						name: 'file',
						success: (uploadFileRes) => {
							uni.hideLoading();
							let data = {}
							if (JSON.parse(uploadFileRes.data).code == 0) {
								data.url = JSON.parse(uploadFileRes.data).data
								this.filePathsList.push(data)
								this.$nextTick(() => {
									this.$emit('inputFun',  JSON.stringify(this.filePathsList))
								})
							} else {
								data.url = JSON.parse(uploadFileRes.data).msg
								this.filePathsList.push(data)
								this.filePathsList.pop()
								uni.showToast({
									title: JSON.parse(uploadFileRes.data).msg,
									icon: "none",
									duration: 2000
								});
								this.$nextTick(() => {
									this.$emit('inputFun',  JSON.stringify(this.filePathsList))
								})
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast("上传失败，请联系开发！")
						},
						complete: function() {
							uni.hideLoading();
						}
					});
				}
			},
		}
	}
</script>

<style lang="less">

</style>